package com.flow.framework.core.validation.validator;

import com.flow.framework.common.exception.ParamCheckedException;
import com.flow.framework.core.validation.annotation.LengthCustomization;
import com.flow.framework.core.validation.validator.base.BaseValidator;

import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Array;

/**
 * Length 校验器
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/1/22
 */
public class LengthValidator extends BaseValidator<LengthCustomization, Object> {
    private LengthCustomization lengthCustomization;

    private int minLen;

    private int maxLen;

    private String errorMsg;

    @Override
    public void initialize(LengthCustomization lengthCustomization) {
        this.lengthCustomization = lengthCustomization;
        this.minLen = lengthCustomization.min();
        this.maxLen = lengthCustomization.max();
        this.errorMsg = "length is not between " + minLen + " and " + maxLen;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (null == value) {
            return true;
        }
        if (value.getClass().isArray()) {
            int len = Array.getLength(value);
            if (len < lengthCustomization.min() || len > lengthCustomization.max()) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(lengthCustomization.errorCode());
            }
            return true;
        }

        if (value instanceof String) {
            int len = ((String) value).length();
            if (len < minLen || len > maxLen) {
                super.logError(context, value, errorMsg);
                throw new ParamCheckedException(lengthCustomization.errorCode());
            }
            return true;
        }
        return false;
    }
}
